package com.jhgsys.internal.common.authentication;

import com.jhgsys.internal.common.utils.SpringContextUtil;
import com.jhgsys.internal.monitor.service.IEhcacheService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class TokenWebSessionManager extends DefaultWebSessionManager {

    /**
     * request请求头属性
     */
    public static final String AUTH_TOKEN ="Authorization";

    public TokenWebSessionManager() {
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String authToken = WebUtils.toHttp(request).getHeader(AUTH_TOKEN);
        if (StringUtils.isEmpty(authToken)){
            return super.getSessionId(request, response);
        } else {
            String sessionId = getSessionIdByToken(authToken);
            if (StringUtils.isEmpty(sessionId)) {
                return null;
            }
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "Stateless request");
            //sessionId
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        }
    }

    private String getSessionIdByToken(String authToken) {
        String sessionId = null;
        IEhcacheService jedisUtils = SpringContextUtil.getBean(IEhcacheService.class);
        //判断Key是否存在
        if (jedisUtils.hasKey(authToken)) {
            sessionId = jedisUtils.get(authToken);
        }
        return sessionId;
    }
}
